/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.dusty.fs.format;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import ru.dusty.fs.filesystem.data.Block;
import ru.dusty.fs.filesystem.data.SuperBlock;
import ru.dusty.fs.filesystem.utils.FsConfig;
import ru.dusty.fs.filesystem.utils.Utils;

/**
 *
 * @author Dusty
 */
public class FormatFs {
    
    private static final String NAME = "format";
    
    private String[] args;
    
    private FsConfig config;
    
    public FormatFs(String[] args) {
        this.args = args;
    }
    
    public int format() {
        if (args.length < 1) {
            System.out.println(NAME + ": missing operand after \"" + NAME + "\"");
            System.out.println(NAME + ": use \"" + NAME + " root\"");
            return 1;
        }
        
        String root = args[0];
        config = new FsConfig(root);
        
        try {
            config.loadConfig();
        } catch (FileNotFoundException ex) {
            System.out.println(NAME + ": Can not find file with the settings.");
            System.out.println(NAME + ": The default settings are loaded.");
            config.loadDefaultConfig();
            //return 4;
        } catch (IOException ex) {
            System.out.println(NAME + ": Error reading settings file.");
            System.out.println(NAME + ": The default settings are loaded.");
            config.loadDefaultConfig();
            //return 4;
        } catch (NumberFormatException ex) {
            System.out.println(NAME + ": Invalid file format settings.");
            System.out.println(NAME + ": The default settings are loaded.");
            config.loadDefaultConfig();
            //return 4;
        }
        
        SuperBlock superBlock = new SuperBlock();
        superBlock.setName(Utils.ROOT_NAME);
        superBlock.setBlockSize(config.getBlockSize());
        superBlock.setBlockCount(config.getBlockCount());
        File file = new File(root + File.separator + "1");
        try {
            Block block = new Block(file);

            block.writeMetaData(superBlock);
            block.close();
        } catch (FileNotFoundException ex) {
            System.out.println(NAME + ": " + file.getPath() + ": failed to open superblock file.");
            return 2;
        } catch (IOException ex) {
            System.out.println(NAME + ": " + file.getPath() + ": error while reading the superblock file.");
            return 3;
        }
        
        System.out.println(NAME + ": format completed successfully.");
        
        return 0;
    }
    
}
